const SUCCESS_CODE = 200
const TOKEN = 'token'
const INFO = 'info'
var timer;  // 定时器
var qrCodeId;
var is_vip = 0
$(function () {
    getLoginInfo()
    // 点击切换
    $("ul.tabBoxSwitchUl").on('click', 'li', function () {
        let i = $(this).index();
        formType(i);
    });
    $(".maskCode button").click(function () {
        formType(1);
    });

    function formType(i) {
        if (i === 0) {
            clearInterval(timer);
            $("form").attr("data-module", "smsFrom");
            $("form button.voice-btn").attr("data-btn", "sms-voice-btn").text("接收语音验证码");
            $("form button.out-login-btn").hide();
            $("form button.fromSubmit").attr("data-type", "smsSubmit").text("注册/登录");
        } else if (i === 1) {
            $(".maskCode").hide();
            $.ajax({
                url: "/api/member/wechatCode",
                method: "GET",
                data: {},
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        $("#wechatImg").attr("src", res.data.qr_code_url);
                        $("form#form_key").hide();
                        $(".ercodeSignBox").show();
                        qrCodeId = res.data.uuid;
                        clearInterval(timer);
                        timer = setInterval(pollingFunction, 2000);
                        setTimeout(function () {
                            clearInterval(timer);
                            $(".maskCode").show();
                        }, 60000)
                    }
                },
                error: function (error) {

                }
            });
        }
    }

    function chooseBtn() {
        $("button[data-type='option']").each(function () {
            $(this).click(function () {
                let txt = $(this).text();
                $("button[data-type='selected']").attr("data-fid", $(this).index());
                $("button[data-type='selected'] span").text(txt);
                $(".selectConentent").hide();
                $(".selectOptions").scrollTop($(this).index() * 40);
            });
            $(this).hover(function () {
                $(this).css("background-color", "#f6f6f6");
            }, function () {
                $(this).css("background-color", "#ffffff");
            });
        });
    };


    //失去焦点;获得焦点
    Focuss($(".msgInput"), "输入 4 位短信验证码");
    Focuss($(".phoneInput"), "手机号");

    Blurr($(".phoneInput"), "请输入手机号");
    Blurr($(".msgInput"), "请输入短信验证码");


    function Focuss(ele, content) {
        ele.focus(function (e) {
            e.preventDefault();
            let _this = $(this);
            _this.parent().removeClass('isShow');
            _this.attr("placeholder", content);
        })
    }

    function Blurr(eleb, contentb) {
        eleb.blur(function (e) {
            e.preventDefault();
            let _this = $(this);
            if (_this.val() == null || _this.val() === "" || _this.val() === undefined) {
                // let content = "请输入短信验证码"
                _this.parent().addClass('isShow').attr('data-content', contentb);
                _this.attr("placeholder", " ");
            } else {
                _this.parent().removeClass('isShow');
            }
        })
    }


    // 60s倒计时
    $(".msgBtn").click(function () {
        let pval = $(".phoneInput").val();
        if (pval == "" || pval == null || pval == undefined) {
            $(".msgBtn").text("重新发送短信验证码");
            let content = "请输入手机号";
            $(".phoneInput").parent().addClass('isShow').attr('data-content', content);
            $(".phoneInput").attr("placeholder", " ");
        } else {
            $(".msgBtn").css("color", "#b7b7b7");
            $(".msgBtn").attr("disabled", true);
            $.ajax({
                url: "/api/member/smsCode",
                method: "POST",
                data: {type: 'send', mobile: pval},
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        getRandom();
                    }
                },
                error: function (error) {

                }
            });
        }
        // getRandom();

    })

    var time = 60;

    function getRandom() {
        if (time === 0) {
            $(".msgBtn").text("发送短信验证码");
            $(".msgBtn").css("color", "#175199");
            $(".msgBtn").attr("disabled", false);
            return
        } else {
            time--;
            $(".msgBtn").text(time + " 秒后可重发");
        }
        setTimeout(function () {
            getRandom();
        }, 1000)

    }

    // 二维码切换登录
    $(".swicth-ercode").click(function (e) {
        $(".maskCode").hide();
        $.ajax({
            url: "/api/member/wechatCode",
            method: "GET",
            data: {},
            dataType: "json",
            success: function (res) {
                if (res.code == 200) {
                    $("#wechatImg").attr("src", res.data.qr_code_url);
                    e.preventDefault();
                    $("form#form_key").hide();
                    $(".ercodeSignBox").show();
                    qrCodeId = res.data.uuid;
                    clearInterval(timer);
                    timer = setInterval(pollingFunction, 2000);
                    setTimeout(function () {
                        clearInterval(timer);
                        $(".maskCode").show();
                    }, 60000)
                }
            },
            error: function (error) {

            }
        });
    });
    $(".switch-input").click(function (e) {
        e.preventDefault();
        $("form#form_key").show();
        $(".ercodeSignBox").hide();
    });

// 轮询函数
    function pollingFunction() {
        let bd_vid = localStorage.getItem('bd_vid');
        let keyword =localStorage.getItem('keyword');
        let a_user =localStorage.getItem('a_user');
        let a_planid=localStorage.getItem('a_planid');
        let a_unitid =localStorage.getItem('a_unitid');
        let a_keywordid = localStorage.getItem('a_keywordid');
        // 向服务器发送 AJAX 请求，获取最新的聊天消息
        $.ajax({
            url: '/api/member/checkScan',
            type: 'GET',
            data: {
                qrCodeId: qrCodeId,
                bd_vid: bd_vid ,
                keyword: keyword,
                userid:a_user,
                planid:a_planid,
                unitid:a_unitid,
                keywordid:a_keywordid
            },
            success: function (res) {
                if (res.code == 200) {
                    localStorage.setItem('token', res.data.token);
                    clearInterval(timer);
                    getLoginInfo()
                    $('#exampleModal').modal('hide')
                    $('#loginButton').hide()
                    $('#header_ac').show()
                }
            },
            error: function () {
                // 处理错误情况
                console.log('Failed to fetch chat messages.');
            }
        });
    }


    // var qrcode = new QRCode('qrcode', {
    //     text: 'your content',
    //     width: 150,
    //     height: 150,
    //     colorDark: '#0084ff',
    //     colorLight: '#ffffff',
    //     correctLevel: QRCode.CorrectLevel.H
    // });
    //
    // function makeCode() {
    //     qrcode.clear();
    //     let txt = '';
    //     qrcode.makeCode(txt);
    // }
});

// 登录提交
function loginSubmit(e) {
    e.preventDefault()
    let phone = $('#phoneInput').val();
    let code = $('#msgInput').val();
    let bd_vid =  localStorage.getItem('bd_vid');
    let keyword =localStorage.getItem('keyword');
    let a_user =localStorage.getItem('a_user');
    let a_planid=localStorage.getItem('a_planid');
    let a_unitid =localStorage.getItem('a_unitid');
    let a_keywordid = localStorage.getItem('a_keywordid');
    if (checkPhoneCode(phone, code)) {
        $.post('/api/member/login', {'mobile': phone,
            'code': code,
            'bd_vid':bd_vid,
            'keyword':keyword,
            'userid':a_user,
            'planid':a_planid,
            'unitid':a_unitid,
            'keywordid':a_keywordid
        }, function (res) {
            if (res.code === SUCCESS_CODE) {
                localStorage.setItem('token', res.data.token);
                $('#exampleModal').modal('hide')
                $('#loginButton').hide()
                $('#header_ac').show()
                window.location.reload()
            } else {
                layer.msg(res.message, {icon: 0, time: 1500});
            }
        })
    }
}

// 用户退出
function userExit() {
    let token = localStorage.getItem(TOKEN)
    if (token) {
        $.ajax({
            url: "/api/member/logout",
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                localStorage.removeItem(TOKEN)
                $('#loginButton').show()
                $('#header_ac').hide()
            }
        });
    }
}

// 检测手机号,验证码
function checkPhoneCode(phone, code) {
    let reg = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
    if (!reg.test(phone)) {
        layer.msg('手机号格式错误', {icon: 0, time: 1500});
        return false;
    }
    if (code === undefined || code === '') {
        layer.msg('验证码错误', {icon: 0, time: 1500});
        return false;
    }
    return true
}

// 获取登录信息
function getLoginInfo() {
    let token = localStorage.getItem(TOKEN)
    if (token) {
        $.ajax({
            url: "/api/member/getInfo",
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                localStorage.setItem(INFO, JSON.stringify(res.data));
                if (res.code === SUCCESS_CODE) {
                    $('#loginButton').hide()
                    $('#header_name').text(res.data.nickname)
                    $('#header_ac').show()
                    // 是否VIP
                    if (res.data.is_vip === 1) {
                        getDayNum();
                        $('#vip').show()
                        $('#not_vip').show()
                        if(res.data.final){
                            $("#not_vip p").eq(0).text("永久会员")
                            $("#not_vip").off("click");
                        }else{
                            $("#not_vip p").eq(0).text(res.data.vip_date+"到期 （点击续费）");
                        }
                        // 是VIP
                        is_vip = 1
                        // 显示继续阅读
                        $('#not-vip-read').hide();
                        $("#not_vip p").eq(1).show();
                        $('#vip-read').show();
                    }else{
                        $("#not_vip p").eq(0).text("开通VIP");
                        $("#not_vip p").eq(1).hide();
                        $('#not_vip').show();
                        $("#haveDownTxt").hide();
                    }
                }
            }
        });
    }
}
